package com.qfedu.sem.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import com.qfedu.sem.dto.BugDto;
import com.qfedu.sem.dto.BugLogDto;
import com.qfedu.sem.dto.BugVersionDto;
import com.qfedu.sem.dto.ProjectDto;
import com.qfedu.sem.service.BugService;
import com.qfedu.sem.service.BugVersionService;
import com.qfedu.sem.service.ProjectService;

import wo.bsys.dto.DictionaryDto;
import wo.bsys.service.DictionaryService;
import wo.bsys.util.BSysConstant;
import wo.bsys.util.BSysUtil;
import wo.bsys.vo.EChartData;
import wo.bsys.vo.EChartSeries;
import wo.bsys.vo.WoDataTable;
import wo.common.entity.WoPage;
import wo.common.util.WoJsonUtil;
import wo.common.util.WoUtil;

@Controller
@RequestMapping("/sem/bug")
@SessionAttributes(BSysConstant.SESSION_USER)
public class BugController {
	private static Logger LOG = LogManager.getLogger(BugController.class);

	@Resource
	private BugService bugService;

	@RequestMapping("/list")
	@ResponseBody
	public WoDataTable<BugDto> getDataTable(Integer draw, Long start, Long length,
			@RequestParam("search[value]") String searchContent, @RequestParam("order[0][dir]") String dir) {
		WoPage<BugDto> page = bugService.getPageData(start, length, searchContent, dir);
		return new WoDataTable<BugDto>(page, draw);
	}

	@RequestMapping("/mylist")
	@ResponseBody
	public WoDataTable<BugDto> getMyDataTable(Integer draw, Long start, Long length,
			@RequestParam("search[value]") String searchContent, @RequestParam("order[0][dir]") String dir,
			String staffType, Map<String, Object> map) {
		WoPage<BugDto> page = bugService.getPageData(start, length, searchContent, dir, BSysUtil.getCurrentUser(map), staffType);
		return new WoDataTable<BugDto>(page, draw);
	}

	@Resource
	private DictionaryService dictionaryService;

	@Resource
	private ProjectService projectService;

	@Resource
	private BugVersionService versionService;

	/**
	 * 故障创建页面的加载
	 * 
	 * @param map
	 * @return
	 */
	@GetMapping("/create")
	String create(Model model) {
		// 设置页面右下方的jsp路径
		// map.put("url", "bug/create.jsp");
		model.addAttribute("url", "bug/create.jsp");
		// 加载数据字典的选项：故障级别和故障频度
		List<DictionaryDto> levels = dictionaryService.getAllByDicType("bugLevel");
		List<DictionaryDto> rates = dictionaryService.getAllByDicType("bugRate");
		// map.put("levels", levels);
		model.addAttribute("levels", levels);
		model.addAttribute("rates", rates);
		// 查询项目和版本
		List<ProjectDto> projects = projectService.getAll();
		List<BugVersionDto> versions = versionService.getAll();
		model.addAttribute("projects", projects);
		model.addAttribute("versions", versions);
		return "main";
	}

	/**
	 * 故障创建页面的提交
	 * 
	 * @param dto
	 * @param imageFile
	 * @param map
	 * @return
	 */
	@PostMapping("/create")
	String create(BugDto dto, MultipartFile imageFile, Map<String, Object> map) {
		bugService.create(dto, imageFile, BSysUtil.getCurrentUser(map));
		return "redirect:/";
	}

	/**
	 * @param map
	 * @return
	 */
	@GetMapping("/update")
	String update(String id, Map<String, Object> map) {
		// 设置页面右下方的jsp路径
		map.put("url", "bug/update.jsp");
		BugDto bug = bugService.getById(id);
		map.put("bug", bug);
		List<BugVersionDto> versions = versionService.getAllByProject(bug.getProjectId());
		map.put("versions", versions);
		return "main";
	}

	@PostMapping("/fix")
	String fix(BugDto dto, Map<String, Object> map) {
		bugService.fix(dto, BSysUtil.getCurrentUser(map));
		return "redirect:/";
	}

	@PostMapping("/test")
	String test(BugDto dto, Map<String, Object> map) {
		bugService.test(dto, BSysUtil.getCurrentUser(map));
		return "redirect:/";
	}

	@GetMapping("/log")
	String log(String id, Map<String, Object> map) {
		// 查询日志
		BugLogDto log = bugService.getLogById(id);
		// 将日志中的content内容，转化为BugDto对象
		BugDto bug = WoJsonUtil.readAsType(log.getContent(), BugDto.class);
		map.put("log", log);
		map.put("bug", bug);
		return "bug/log";
	}

	@Resource
	@Qualifier("bugExportView")
	private View bugExportView;

	@GetMapping("/export")
	ModelAndView export() {
		ModelAndView m = new ModelAndView();
		List<BugDto> bugs = bugService.getAll();
		m.addObject("bugs", bugs);
		m.setView(bugExportView);
		return m;
	}

	/**
	 * 加载故障统计页面的项目下拉框数据
	 * 
	 * @param map
	 * @return
	 */
	@GetMapping("/projects")
	String getProjects(Map<String, Object> map) {
		map.put("projects", projectService.getAll());
		return "bug/projects";
	}

	@GetMapping("/charts")
	@ResponseBody
	EChartData loadChartData(String projectId, String currentNode) {
		// 构造图表数据
		EChartData data = new EChartData();
		// 设置图例
		data.setLegends(Arrays.asList("数量"));
		// 获取各版本的故障数量
		Map<String, Integer> bugs = bugService.getBugsByVersion(projectId, currentNode);
		// 获取版本数据，作为X轴
		List<String> xAxis = new ArrayList<String>();
		for (String x : bugs.keySet()) {
			xAxis.add(x);
		}
		Collections.sort(xAxis);
		data.setxAxis(xAxis);
		// 设置系列数据：故障数
		List<Double> seriesData = new ArrayList<Double>();
		for (String x : xAxis) {
			seriesData.add(Double.valueOf(bugs.get(x)));
		}
		data.setSeries(Arrays.asList(new EChartSeries("数量", seriesData)));
		return data;
	}
	
	@RequestMapping("/image/{id}")
	ResponseEntity<byte[]> loadImage (@PathVariable ("id") String bugId) {
		BugDto bug = bugService.getById(bugId);
		if (WoUtil.isEmpty(bug.getImage())) {
			return null;
		}
		File f = new File (BugService.root + bug.getImage());
		HttpHeaders header = new HttpHeaders();
		header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		int index = bug.getImage().lastIndexOf('/');
		String imageName = bug.getImage().substring(index + 1);
		try {
			imageName = new String (imageName.getBytes("UTF-8"), "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			LOG.error("解析文件名出错", e);
		}
		ResponseEntity<byte[]> re;
		try {
			re = new ResponseEntity<byte[]>(FileCopyUtils.copyToByteArray(f), header, HttpStatus.OK);
		} catch (IOException e) {
			LOG.error("解析文件出错", e);
			return null;
		}
		return re;
	}
}
